<?php

namespace app\api\model;

use think\Db;
use think\Exception;
use think\Model;

class User extends Model
{

    protected $pk = 'user_id';

    public static function GetRandStr($length)
    {
        //字符组合
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len = strlen($str) - 1;
        $randstr = '';
        for ($i = 0; $i < $length; $i++) {
            $num = mt_rand(0,$len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }

    public static function queryByUserNumber($userNumber)
    {
        $where['user_number'] = $userNumber;
        $where['status'] = 1;
        $user = User::where($where)->field('user_id,password,username,user_number,salt,group_id,phone')->find();
        return $user;
    }

    public static function comparePwd($password, $pwd)
    {
        return md5($password) === $pwd;
    }

    public static function createUser($params)
    {

        $data = [
            'user_number' => $params['user_number'],
            'username' => $params['username'],
            'password' => md5($params['password']),
            'salt' => self::GetRandStr(6),
            'phone' => $params['phone'],
            'group_id' => 10001,
            'status' => 1,
            'create_time' => date("Y-m-d H:i:s", time()),
            'update_time' => date("Y-m-d H:i:s", time()),
        ];

        $relationData = [
            'department_id' => $params['department_id'],
            'major_id' => $params['major_id'],
            'class_id' => $params['class_id']
        ];

        Db::startTrans();
        try {
            $user_id = self::insertGetId($data);
            $relationData['user_id'] = $user_id;
            UserRelation::createRelation($relationData);
            Db::commit();
        } catch (Exception $e) {
            dump($e->getMessage());
            Db::rollback();
            return false;
        }
        return true;
    }

    public static function queryByUserId($userId,$groupId)
    {
        switch ($groupId){
            case 10001:
                $User = new User();
                $where1['u.user_id'] = $userId;
                $where1['u.status'] = 1;
                $user = $User->alias('u')->where($where1)
                    ->join('stu_user_relation ur','u.user_id = ur.user_id','left')//关系表
                    ->join('stu_major m','ur.major_id = m.major_id','left')//专业表
                    ->join('stu_department d','ur.department_id = d.id','left')//学员表
                    ->join('stu_class cs','ur.class_id = cs.class_id','left')//班级表
                    ->field('u.*,m.major_name,d.name as department_name,cs.class_name')
                    ->find();
                break;
            default:
                $where['user_id'] = $userId;
                $where['status'] = 1;
                $user = User::where($where)->find();
                break;
        }

        return $user;
    }

}